<template>
    <div class="home">
        <div class="search">
            <!-- 输入搜索功能 -->
            <div class="input">
                <input type="text" placeholder="请输入城市名称" v-model="keyword" @input="handleInput">
                <div class="display"></div>
            </div>
            <div v-if="searchResults.length > 0">
                <div class="list" v-for="item in searchResults" :key="item.adcode" @click="searchCity(item)">{{
                    item.city }}
                </div>
            </div>
            <div class="list" v-else-if="searchResults.length === 0 && keyword.trim() != ''">似乎没有找到你查询的城市</div>
        </div>
        <!-- 渲染列表功能 -->
        <div class="cityList">
            <div v-if="cityList.length > 0">
                <div class="city" v-for="city in cityList" :key="city.adcode">
                    <div class="city1">
                        <span>{{ city.name }}</span>
                        <span>{{ city.tem }}度</span>
                    </div>
                    <span class="detail" @click="handleDetail(city)">查看</span>
                    <span class="delete" @click="handleDelete(city.adcode)">删除</span>
                </div>
            </div>
            <div class="none" v-else-if="cityList.length === 0">暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</div>
        </div>
        <div class="fore">
            <h2>近期天气</h2>
            <forecast />
            <!-- 引入图表组件 -->
        </div>
    </div>
</template>
<script setup>
import forecast from '../components/forecast.vue'
import { getAdcode } from '../api/weather.js'
import { ref, onMounted } from 'vue'
const adcode = ref({})
const keyword = ref('')
const searchResults = ref([]) // 用于存储搜索建议结果的数组

// 从pinia中读取数据后渲染列表
import { useCityStore } from '../stores/cityList.js'
import { storeToRefs } from 'pinia'
// 解构数组
const { cityList, isAddVisible, titleVisible } = storeToRefs(useCityStore())   //加号的状态  cityview页面的标题span
const { deleteCity } = useCityStore()


import { useRouter } from "vue-router";
const router = useRouter()

// 输入的时候发送axios请求获取城市adcode
const handleInput = async () => {
    // 检查关键词是否为空，避免发送无意义的请求
    if (keyword.value.trim() === '') {
        searchResults.value = []; // 清空搜索结果
        return;
    }
    // 调用 getAdcode 接口
    const resData = await getAdcode(keyword.value);

    if (resData && resData.status === '1' && Array.isArray(resData.geocodes)) {
        // API成功且返回了 geocodes 数组（即使是空数组 []）

        // 新增过滤逻辑：只保留城市级别（level为"市"或者省）的结果
        const cityResults = resData.geocodes.filter(item => item.level === '市' || item.level === '省')

        searchResults.value = cityResults;
        // console.log(searchResults.value)
    } else {
        // API返回错误，或者没有找到匹配结果（geocodes 字段缺失或非数组）
        // console.warn('API返回错误或数据结构异常:', resData ? (resData.info || resData) : '无响应数据');
        searchResults.value = []; // 确保赋值为空数组 []
    }
}

// searchCity  这里来实现根据搜索结果来跳转路由 并传递参数
const searchCity = (item) => {
    titleVisible.value = true
    isAddVisible.value = true
    router.push({ path: '/city', query: { adcode: item.adcode, city: item.city } })
}



// console.log(cityList)

// 查看按钮：点击的具体的城市列表 查看按钮可以跳转到具体信息
const handleDetail = (city) => {
    titleVisible.value = false
    isAddVisible.value = false
    router.push({ path: '/city', query: { adcode: city.adcode, city: city.name } })
}

// 点击删除按钮后调用pinia中的函数删除中的内容
const handleDelete = (adcode) => {
    deleteCity(adcode)
}

</script>
<style lang="scss" scoped>
.home {
    width: 960px;
    margin: 0 auto;
    background-color: #00668a;

    .search {
        .list {
            display: flex;
            align-items: center;
            width: 960px;
            height: 60px;
            padding: 8px 0;
            background-color: #004e71;
            color: #ffffff;
            margin-top: 8px;
            cursor: pointer;
        }
    }

    input {
        width: 960px;
        height: 40px;
        padding: 8px 4px;
        margin-top: 15px;
        background-color: #00668a;
        border: 0;
        border-bottom: 1px solid #ffffff;
        outline: none;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        font-size: 16px;
        color: #ffffff;

        &::placeholder {
            color: #9c9399;
            font-size: 16px;
        }

        &:focus {
            box-shadow:
                0 4px 8px rgba(0, 0, 0, 0.2), // 加深阴影
                0 1px 0 rgba(255, 255, 255, 0.1) inset;
            border-bottom: 0;
        }
    }

    .cityList {
        margin-top: 20px;

        .none {
            color: #ffffff;
            display: flex;
            justify-content: center;
        }

        .city {
            display: flex;
            align-items: center;
            width: 960px;
            height: 40px;
            padding: 8px 0;
            margin-bottom: 16px;
            // background-color: #004e71;
            color: #ffffff;

            .city1 {
                width: 960px;
                height: 40px;
                padding: 0 16px;
                // margin-right: 10px;
                border-radius: 3px;
                display: flex;
                align-items: center;
                justify-content: space-between;
                background-color: #004e71;
            }

            .detail,
            .delete {
                display: none;
                cursor: pointer;
                border-radius: 3px;
                margin-left: 10px;
                width: 80px;
                height: 40px;
                // display: flex;
                // align-items: center;
                text-align: center;
                line-height: 40px;
                background-color: #eab308;
                font-size: 15px;
            }

            &:hover .detail,
            &:hover .delete {
                display: inline-block;
            }
        }
    }

    .fore {
        padding-top: 20px;

        h2 {
            color: #ffffff;
        }
    }
}
</style>